package me.zhengjie.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.utils.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class WebAspect {

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object request(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return pjp.proceed();
        }
        HttpServletRequest request = requestAttributes.getRequest();
        this.printRequestLog(request, pjp);
        return pjp.proceed();
    }

    /**
     * 获取接口访问参数
     **/
    private void printRequestLog(HttpServletRequest request, JoinPoint jp) {
        String ip = StringUtils.getIp(request);;
        String url = request.getRequestURI();
        Object[] args = jp.getArgs();
        String params = null;
        try {
            params = JSON.toJSONString(args);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        log.info("request info [{},{}], params:[{}]",ip, url, params);
    }

}
